package at.fhooe.SRWCProject.WiFiDirect.Socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.os.Handler;
import at.fhooe.SRWCProject.WiFiDirect.ShareFileActivity;

public class ConnectionThread extends Thread {
	Socket mmSocket;
	private final Handler mmHandler;
	private InputStream mmInStream;
	private OutputStream mmOutStream;
	
	public InetAddress getInetAddress() {
		return mmSocket.getInetAddress();
	}
	
	public InetAddress getLocalInetAddress() {
		return mmSocket.getLocalAddress();
	}

	public ConnectionThread(Socket socket, Handler handler) {
		super();
		mmSocket = socket;
		mmHandler = handler;
		try {
			mmInStream = mmSocket.getInputStream();
			mmOutStream = mmSocket.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		byte[] buffer = new byte[1024];
		int len;
		while (true) {
			try {
				len = mmInStream.read(buffer);
				String data = new String(buffer, 0, len);
				mmHandler.obtainMessage(ShareFileActivity.DATA_RECEIVED, data).sendToTarget();
			} catch (IOException e) {
				e.printStackTrace();
				if (!mmSocket.isConnected()) {
					break;
				}
			}
		}
	}

	public void write(byte[] bytes) {
		try {
			mmOutStream.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void cancel() {
		try {
			mmSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}